package com.t.common;

import java.io.ByteArrayInputStream;
import java.util.*;

/**
 * Created by Administrator on 2018/5/31.
 */
public class lockUtil {
    private static boolean hasLocked=false;
    private static  HashMap<String, Calendar> lockMap = new HashMap<String,Calendar>();
    private static  int seleepInt=50;
    private static  int maxInt=10;

    private synchronized static boolean setLockMap(String lockIdentity)
    {
        Calendar calendar = Calendar.getInstance();
        if (lockMap.containsKey(lockIdentity))
        {
            Calendar dateEnd=lockMap.get(lockIdentity);
            if (calendar.compareTo(dateEnd)==1)
            {
                calendar.add(Calendar.SECOND, maxInt);
                lockMap.put(lockIdentity, calendar);
                return true;
            }
            else
            {
                return  false;
            }
        }
        else
        {
            calendar.add(Calendar.SECOND, maxInt);
            lockMap.put(lockIdentity, calendar);
            return true;
        }
    }

    public static boolean Lock(String lockIdentity)
    {
        try
        {
            //1234
            boolean result = false;
            while ( !result)
            {
                result = setLockMap(lockIdentity);
                if (!result)
                {
                    Thread.sleep(seleepInt);
                }
                else
                {
                    hasLocked = true;
                    break;
                }
            }
            return hasLocked;
        }catch (InterruptedException e) {
            return true;
        }
        catch(Exception e)
        {
            return true;
        }
    }
    public static void UnLock(String lockIdentity)
    {
        lockMap.remove(lockIdentity);
    }
}
